#include "Widget.h"
#include "../common/utils/FileChecker.h"
#include "SDL/SDL_gfxPrimitives.h"
#include "../common/utils/SurfaceUtils.h"

void Widget::initParcel(int posX, int posY)
{
	parcel = new Parcel();
	parcel->updateXY(posX,posY);
	parcel->updateHW(0,0);

    if(this->surface !=NULL){
    	parcel->updateHW(this->surface->h,this->surface->w);
    }
}

Widget::Widget(int posX, int posY, SDL_Surface* surface, Widget *parent, bool drawBorders,Color borderColor) {
	this->parcel = NULL;
	this->parent = parent;
	this->surface = surface;
	this->drawBorders = drawBorders;
	this->borderColor = borderColor;
    initParcel(posX, posY);
}

Widget::Widget(Color color, int w,int h,int posX, int posY, Widget *parent, bool drawBorders){
	this->parcel = NULL;
	this->parent = parent;
	this->surface = SurfaceUtils::colorSurface(w,h,color);
	this->drawBorders = drawBorders;
	this->borderColor = Color::AZUL;
	initParcel(posX, posY);
}

Widget::Widget(int posX, int posY, std::string imageSurface, Widget *parent, bool drawBorders) {
	this->parcel = NULL;
	this->parent = parent;
	this->surface = SurfaceUtils::loadImage(imageSurface);
	this->drawBorders = drawBorders;
	this->borderColor = Color::AZUL;
	initParcel(posX,posY);
}

SDL_Rect Widget::getPosition() {
	SDL_Rect rectangle = parcel->getRectangle();
	if (parent != NULL) {
		SDL_Rect rectangleParent = parent->getPosition();
		rectangle.x += rectangleParent.x;
		rectangle.y += rectangleParent.y;
	}

	return rectangle;
}

Widget::~Widget() {
	if (surface != NULL) {
		SDL_FreeSurface(surface);
		surface = NULL;
	}
	delete parcel;
}

void Widget::handleEvent(Event event){}

void Widget::resolve(){}

void Widget::showOn(SDL_Surface *canvasSurface){

	Uint32 vLineColor = borderColor.getColor();

	SDL_Rect rectangle = parcel->getRectangle();
	if(this->surface){
		if(this->drawBorders){
			vlineColor(this->surface, 0, 0, rectangle.h, vLineColor);
			vlineColor(this->surface, rectangle.w-1, 0, rectangle.h, vLineColor);
			hlineColor(this->surface, 0, rectangle.w, 0, Color::AZUL);
			hlineColor(this->surface, 0, rectangle.w, rectangle.h-1, vLineColor);
		}
		SDL_Rect rect = this->parcel->getRectangle();
		SDL_BlitSurface(this->surface, NULL, canvasSurface, &rect);
	}else{
		if(this->drawBorders){
			vlineColor(canvasSurface, rectangle.x, rectangle.y, rectangle.h, vLineColor);
			vlineColor(canvasSurface, rectangle.x + rectangle.w-1, rectangle.y, rectangle.h, vLineColor);
			hlineColor(canvasSurface, rectangle.x, rectangle.w, rectangle.y, vLineColor);
			hlineColor(canvasSurface, rectangle.x, rectangle.w, rectangle.y + rectangle.h-1, vLineColor);
		}
	}
}

bool Widget::isMouseOver(Event event) const {
	SDL_Rect rectangle = parcel->getRectangle();
	return ((event.getXCoordinate() > rectangle.x)
			&& (event.getXCoordinate() < rectangle.x + rectangle.w)
			&& (event.getYCoordinate() > rectangle.y)
			&& (event.getYCoordinate() < rectangle.y
					+ rectangle.h));
}
